/**
 * Author liuyang46@meituan.com
 * Date 16/5/5
 * Describe
 */
'use strict'
const cheerio = require('cheerio');
const superagent = require('superagent');
const co = require('co');
const fs = require('fs');

const ziroomHost = 'http://www.ziroom.com';
let roomListUrl = [
    {
        name: '望京',
        url: 'http://www.ziroom.com/z/nl/o4-d23008613-b18335711-z2-r0TO3000.html'
    },
    {
        name: '立水桥',
        url: 'http://www.ziroom.com/z/nl/d23008611-b18335744-z2-r0TO3000.html'
    },
    {
        name: "龙泽",
        url: 'http://www.ziroom.com/z/nl/d23008611-b611100311-z2-r0TO3000.html'
    },
    {
        name: '育新',
        url: 'http://www.ziroom.com/z/nl/sub/s8%E5%8F%B7%E7%BA%BF-t%E8%82%B2%E6%96%B0-z2-r0TO3000.html'
    },
    {
        name: '惠新西街',
        url: 'http://www.ziroom.com/z/nl/d23008613-b611100324-z2-r0TO3000.html'
    },
    {
        name: '15号线',
        url: 'http://www.ziroom.com/z/nl/sub/s15%E5%8F%B7%E7%BA%BF-z2-r0TO3000.html'
    },
    {
        name: '北苑',
        url: 'http://www.ziroom.com/z/nl/sub/s13%E5%8F%B7%E7%BA%BF-t%E5%8C%97%E8%8B%91-z2-r0TO3000.html'
    },
    {
        name: '15号线-望京',
        url: 'http://www.ziroom.com/z/nl/sub/s15%E5%8F%B7%E7%BA%BF-t%E6%9C%9B%E4%BA%AC-z2-r0TO3000.html'
    }

]

let startGn = co.wrap(function*() {
    let houseList = [];
    for (let i = 0; i < roomListUrl.length; i++) {
        let roomUrl = roomListUrl[i];
        let house = [];
        let now = 1;
        while (true) {
            let result = yield getList(`${roomUrl.url}?p=${now}`);
            house = house.concat(result.houseList);
            if (result.pages.now == result.pages.total) {
                break;
            } else {
                now++;
            }
        }
        house = yield outScheduleRoom(house);
        console.log('清理已经预定房屋完毕');
        houseList.push({
            list: house,
            name: roomUrl.name,
            time: Date.now()
        })
    };

    fs.writeFile('./houselist.json', JSON.stringify(houseList), function (err) {
        if (err) {
            console.error(err);
            return;
        }
        console.log('解析成功,已写入');
    })

});

start();

function start(){
    startGn().then(function(){
        console.log('抓取完毕,等待1H后重新抓取');
        setTimeout(function(){
            start();
        },60*60*1000);
    }).catch(function(error){
        console.error(error.stack);
    });
}




function *outScheduleRoom(list) {
    let scheduleList=[];
    for (let i = 0; i < list.length; i++) {
        let item = list[i];
        let url = item.href;
        yield new Promise((resolve,reject)=>{
            superagent.get(url)
                .set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36")
                .end((err, res)=> {
                    console.log(`是否预定:${item.name}`)
                    if (err) {
                        reject(err);
                        return;
                    }
                    const $ = cheerio.load(res.text);
                    let schedule = $('#zreserve').text() == '我要看房';
                    if(schedule){
                        scheduleList.push(item);
                    }
                    resolve(1);
                });
        });
    }
    return scheduleList;
}

function getList(url) {
    return new Promise((resolve, reject)=> {
        superagent.get(url)
            .set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36")
            .end((err, res)=> {
                console.info(`已完成:${url}`);
                if (err) {
                    reject(err);
                    return;
                }
                const $ = cheerio.load(res.text);
                let houseList = analysisHousing($);
                let pages = analysisPages($);
                resolve({houseList, pages});
            });
    });

}

/**
 * 分析房屋列表
 */
function analysisHousing($) {

    let houseList = [];

    // 房屋列表
    let list = $('.t_newlistbox #houseList>li');
    list.each((index, element)=> {
        let item = $(element);
        let href = ziroomHost + item.find('.img>a').attr('href');
        let imgSrc = item.find('.img img').attr('src');
        let name = item.find('.txt>h3>a').text();
        let area = item.find('.txt>.detail>p').first().find('span').eq(0).text();
        let floor = item.find('.txt>.detail>p').first().find('span').eq(1).text();
        let pattern = item.find('.txt>.detail>p').first().find('span').eq(2).text();
        let tags = item.find('.txt>.room_tags').html();

        let price = item.find('.priceDetail>.price').text().match(/\d+/)[0]; //价格
        let priceRatio = price / parseFloat(area);
        houseList.push({
            href, imgSrc, name, area, floor, pattern, tags, price, priceRatio
        })
    });
    return houseList;
}
/**
 * 分析分页
 * @param $
 */
function analysisPages($) {
    let list = $('#page');
    if (list.html().trim() == '') {
        return {
            now: 1,
            total: 1
        }
    }
    let now = parseInt(list.find('a.active').text());
    // let total = list.find('span').first().text().match(/\d+/)[0];
    let total = list.find('a').last().next('span').text().match(/\d+/)[0];
    return {
        now,
        total
    }
}

// getList(ziroomListUrl)